package cn.alone.pet.service.impl;
import cn.alone.basic.service.impl.BaseServiceImpl;
import cn.alone.pet.domain.Pet;
import cn.alone.pet.domain.PetDetail;
import cn.alone.pet.mapper.PetDetailMapper;
import cn.alone.pet.mapper.PetMapper;
import cn.alone.pet.service.IPetService;
import cn.alone.user.domain.Logininfo;
import cn.alone.user.domain.User;
import cn.alone.user.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author lanan
 */
@Service
public class PetServiceImpl  extends BaseServiceImpl<Pet> implements IPetService {

    @Autowired
    private PetMapper petMapper;
    @Autowired
    private PetDetailMapper petDetailMapper;
    @Autowired
    private UserMapper userMapper;

    @Override
    public Pet loadByIdDetail(Long id) {
        return petMapper.loadByIdDetail(id);
    }

    /**
     * 领养宠物
     * @param id
     * @param logininfo
     */
    @Override
    public void adopt(Long id, Logininfo logininfo) {
        /*宠物被领养需要改状态*/
        Pet pet = petMapper.loadById(id);
        pet.setState(0);
        /*需要返回领养操作时间*/
        pet.setOnsaletime(new Date());
        /*给pet表格绑定用户的id*/
        User user = userMapper.loadByLogininfoId(logininfo.getId());
        pet.setUser_id(user.getId());
        petMapper.update(pet);
    }

    /**
     * 上架宠物
     * @param ids
     */
    @Override
    public void onSale(List<Long> ids) {
        Map<String,Object> map = new HashMap<>();
        map.put("ids", ids);
        /*返回时间戳*/
        map.put("onsaletime", new Date());
        petMapper.onSale(map);
    }

    /**
     * 下架宠物
     * @param ids
     */
    @Override
    public void offSale(List<Long> ids) {
        Map<String,Object> map = new HashMap<>();
        /*前端需要显示操作时间*/
        map.put("offsaletime",new Date());
        map.put("ids", ids);
        petMapper.offSale(map);

    }

    @Override
    public void add(Pet pet) {
        /*保存宠物信息返回自增长id交给petDetail*/
        petMapper.save(pet);
        /*保存宠物详情信息,有可能前端不填宠物详情值修改宠物状态,所以要判断是否为空*/
        if (pet.getDetail()!=null){
            PetDetail petDetail = pet.getDetail();
            petDetail.setPet_id(pet.getId());
            petDetailMapper.save(petDetail);
        }
    }
}
